import * as https from 'https';

export const hostname: string = "china.nba.com";

export interface INbaReqConfig {
    "playerdata": (playername: string) => string;
    "teamdata": (series: string,schedule:string) => string;
    "team": string;
    "playerlist": string;
    "teamrank": string;
}

export interface INbaReqOption {
    "hostname": string;
    "port"?: number;
    "path": string;
    "method"?: string;
}

export type INbaReq = () => Promise<void>;

export type experience = "All" | "Rookie" | "Sophomore"; // 全部 | 新秀 | 二年

export type position = "All" | "G" | "F" | "C"; // 全部 | 后卫 | 前锋 | 中锋

export type form = "points" | "rebounds" | "assists" | "blocks" | "steals" | "fouls" | "turnovers" | "mins" | "efficiency" | "fgpct" | "tppct" | "ftpct"; // 得分 | 篮板 | 助攻 | 盖帽 | 抢断 | 犯规 | 失误 | 分钟 | 效率 | 投篮 | 三分 | 罚球

export type series = "1996" | "1997" | "1998" | "1999" | "2000" | "2001" | "2002" | "2003" | "2004" | "2005" | "2006" | "2007" | "2008" | "2009" | "2010" | "2011" | "2012" | "2013" | "2014" | "2015" | "2016" | "2017" | "2018"; // 1996-1997 1997-1998 1998-1999 1999-2000 2000-2001 2001-2002 2002-2003 2003-2004 2004-2005 2005-2006 2006-2007 2007-2008 2008-2009 2009-2010 2010-2011 2011-2012 2012-2013 2013-2014 2014-2015 2015-2016 2016-2017 2017-2018 2018-2019 

export type schedule = "1" | "2" | "4"; // 季前赛 | 常规赛 | 季后赛

export type mold = "perGame" | "total"; // 场均  | 总数

export type area = "All" | "eastern" | "western"; // 全部 | 东部 | 西部

export const nbaReqConfig: INbaReqConfig = {
    "team": "/static/data/league/conferenceteamlist.json",
    "playerlist": "/static/data/league/playerlist.json",
    "teamrank": "/static/data/season/conferencestanding.json",
    "playerdata": (playername: string): string => {
        return `/static/data/player/stats_${playername.trimLeft().trimRight().replace(/\s+/g,'_')}.json`;
    },
    "teamdata": (series:string = "2018" , schedule:string = "4"): string => {
        return `/static/data/league/teamstats_All_All_${series}_${schedule}.json`
    }
}

export const nbaReq = (options: INbaReqOption): Promise<string> => {
    return new Promise((resolve,reject) => {
        let resultBuffer = Buffer.allocUnsafe(0); // 处理乱码
        let result = '';
        try {
            const req = https.request(options, res => {
                res.on('data', (chunk) => {resultBuffer = Buffer.concat([resultBuffer, chunk], resultBuffer.length + chunk.length);});
                res.on('end', () => {
                    result = resultBuffer.toString();
                    resolve(result);
                });
            })
    
            req.on("error", error => {
                console.log(error);
            })
    
            req.end();
        } catch (error) {
            console.log(`request player data error : ${error}; option=${JSON.stringify(options)}`);
        }
    })
}